package routers

import (
	//"github.com/didip/tollbooth"
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	"io"
	"os"
	_ "shop-admin/docs"
	"shop-admin/middleware"
	"shop-common/library/env"
	"shop-common/library/variables"
	sysRouter "shop-sys/router"
)

func InitWebRouter(accessInfoLogger, accessErrLogger io.Writer) *gin.Engine {
	var router *gin.Engine
	// 非调试模式（生产模式） 日志写到日志文件
	if !variables.AppDebug {
		//1.将日志写入日志文件
		gin.DefaultWriter = io.MultiWriter(os.Stdout, accessInfoLogger)
		gin.DefaultErrorWriter = io.MultiWriter(os.Stderr, accessErrLogger)
		// 2.如果是有nginx前置做代理，基本不需要gin框架记录访问日志，开启下面一行代码，屏蔽上面的三行代码，性能提升 5%
		//gin.SetMode(gin.ReleaseMode)
		router = gin.Default()
	} else {
		// 调试模式，开启 pprof 包，便于开发阶段分析程序性能
		router = gin.Default()
		pprof.Register(router)
	}

	return adminRouter(router)
}

func adminRouter(router *gin.Engine) *gin.Engine {
	router.Use(middleware.Cors())
	router.Use(middleware.Secure())
	//router.Use(middleware.Logger())
	//router.Use(middleware.RequestLog(loggerV2.GetLogZap()))

	//router.StaticFS("/img", http.Dir("../static"))
	router.Static("/static", variables.ZoneSetting.Local.ImagePath)
	//rate-limit 中间件
	//lmt := tollbooth.NewLimiter(500, nil)
	//lmt.SetMessage("服务繁忙，请稍后再试...")

	if env.IsDevMode() {
		// http://127.0.0.1:9001/swagger/index.html 文档界面访问UR
		router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	}

	publicGroup := router.Group("")
	{
		sysRouter.PublicCaptcha(publicGroup)
		sysRouter.PublicSysUser(publicGroup)
	}

	// todo 权限中间件后期需要把不需要token及不需要casbin的剃出来
	//middleware.PermissionAuth()
	//privateGroup := router.Group("", middleware.LimitHandler(lmt))
	privateGroup := router.Group("")
	privateGroup.Use(middleware.JWTAuth())
	{
		privatePicture(privateGroup)
		privateFile(privateGroup)
		privatePickAddr(privateGroup)
		privateSystemStore(privateGroup)
		privateIndexImg(privateGroup)
		privateNotice(privateGroup)
		privateArea(privateGroup)

		privateUser(privateGroup)
		privateProduct(privateGroup)
		privateCategory(privateGroup)

		privateStoreCategory(privateGroup)
		privateProdTag(privateGroup)
		privateStoreProduct(privateGroup)
		privateStoreProductRule(privateGroup)

		privateTransport(privateGroup)

		privateShippingTemplates(privateGroup)
		privateSettingCity(privateGroup)
		sysRouter.PrivateSysUser(privateGroup)
		sysRouter.PrivateSysMenu(privateGroup)
		sysRouter.PrivateSysRole(privateGroup)
		sysRouter.PrivateSysXhr(privateGroup)
		sysRouter.PrivateSysLog(publicGroup)
	}

	return router
}
